import { bus } from "@/bus";
import { loadConfig } from '@/config.ts'
import { Gateway } from "@/entity/gateway.entity";
import { DataSource } from "typeorm";
import * as state from '../state'
import { Wristband } from "@/entity/wristband.entity";
import { createAdv } from "./wristbandAdv";
import { saveLastAdv } from "./wristbandLastAdv"
import { WristbandAdv } from "@/entity/wristband_adv.entity";
import { WristbandAdvLast } from "@/entity/wristband_adv_last.entity";
import { updateGw } from "./gateway";
import { updateWristband } from "./wristband";


export async function setup(AppDataSource: DataSource | null) {
  let conf = await loadConfig();

  const gatewayRepo = AppDataSource ? AppDataSource.getRepository(Gateway) : null;
  const wristbandRepo = AppDataSource ? AppDataSource.getRepository(Wristband) : null;
  const wristbandAdvRepo = AppDataSource ? AppDataSource.getRepository(WristbandAdv) : null;
  const wristbandLastAdvRepo = AppDataSource ? AppDataSource.getRepository(WristbandAdvLast) : null;

  let macCount: { [key: string]: { count: number, rssiSum: number } } = {};


  bus.on('wb.adv.decode', async (pack: any) => {
    const gw = {
      mac: pack.mac,
      version_bin: pack.frm_ver.split('/')[0],
      version_fs: pack.frm_ver.split('/')[1],
      time: new Date(),
      last_report_time: new Date(),
      last_report_wb_cnt: pack.wb_adv.length,
      deleted: false,
      outdoor: false,
    };

    const wbArray = pack.wb_adv.map((item: any) => {
      return {
        addr: item.mac.toUpperCase(),
        rssi: item.rssi | 1000000000,
        idx: item.idx,
        beacon1: item.beacon1,
        beacon2: item.beacon2,
        beacon3: item.beacon3,
        acc_x: 0,
        acc_y: 0,
        acc_z: 0,
        motion: item.motion || 0,
        motion_variance: item.motion_variance || 0,
        steps: item.steps,
        hr: item.hr,
        hrv: item.hrv,
        hr_confidence: item.hr_confidence,
        temperature: item.temp,
        bat_vol: item.bat_vol,
        charging: item.charging,
        wear_on: item.wear_on,
        req_rt: item.req_rt,
        fake_hr: item.fake_hr,
        time: new Date(),
        format: item.format_ver,
        version: item.firmware_ver,
        name: 'c1',
        deleted: false,
      };
    });



    // 统计每个MAC的出现次数和RSSI总和
    wbArray.forEach((item: any) => {
      if (!macCount[item.addr]) {
        macCount[item.addr] = { count: 0, rssiSum: 0 };
      }
      macCount[item.addr].count += 1;
      macCount[item.addr].rssiSum += item.rssi;
    });




    if (AppDataSource && gatewayRepo) {
      await updateGw(gw, gatewayRepo);
    }
    if (wristbandRepo) {
      await updateWristband(wbArray, wristbandRepo);
    }
    try {
      for (const item of wbArray) {
        await updateWristbandAdv(gw, item);
      }
    } catch (err) {

    }

  });

  async function updateWristbandAdv(gw: state.GwObject, val: state.WbArray) {
    try {
      if (wristbandRepo && wristbandAdvRepo && wristbandLastAdvRepo) {
        await createAdv(gw.mac, val.addr.toUpperCase(), val.rssi || -1000000, val, val.format || 111111, new Date(), wristbandRepo, wristbandAdvRepo);
        await saveLastAdv(gw.mac, val.addr.toUpperCase(), val.rssi || -1000000, val, val.format || 111111, new Date(), wristbandRepo, wristbandLastAdvRepo);
      }
    } catch (err) {
      console.log('err', err);
    }
  }
}







